import { EllipsisOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable, TableDropdown } from '@ant-design/pro-components';
import {Button, Dropdown, message, Space, Switch, Tag} from 'antd';
import {useRef, useState} from 'react';
import Avatar from "antd/es/avatar/avatar";
import {deleteUser, search, updateUser} from "@/services/ant-design-pro/api";
export const waitTimePromise = async (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export const waitTime = async (time: number = 100) => {
  await waitTimePromise(time);
};
// eslint-disable-next-line react-hooks/rules-of-hooks

type GithubIssueItem = {
  username: string;
  userAccount: string;
  avatarUrl: string;
  gender: number;
  phone: string;
  email: string;
  userStatus: string;
  createTime: string;
  userRole : number;
};
const showMessage = function (result: boolean,messages : string){
  if (result){
    message.success(messages)
  }else {
    message.error(messages)
  }
}
const updateRow = async function(record: API.CurrentUser){
  const flag = await updateUser({
    ...record
  })
  if (flag){
    message.open({
      type : 'success',
      content : '修改成功'
    })
  }else {
    message.open({
      type : 'error',
      content : '修改失败'
    })
  }
}
const columns: ProColumns<GithubIssueItem>[] = [
  {
    title: '序号',
    dataIndex: 'index',
    valueType: 'indexBorder',
    width: 48,
  },
  {
    disable: true,
    title: '昵称',
    dataIndex: 'username',
    copyable: true,
    ellipsis: true,
  },
  {
    disable: true,
    title: '账号',
    dataIndex: 'userAccount',
    editable: false,
    copyable: true,
    ellipsis: true,
  },
  {
    disable: true,
    title: '头像',
    dataIndex: 'avatarUrl',
    search: false,
    renderFormItem: (_, { defaultRender }) => {
      return defaultRender(_);
    },
    render: (_, record) => (
      <Space>
        <Avatar size={"small"} src={record.avatarUrl} />
      </Space>
    ),
  },
  {
    title: '性别',
    dataIndex: 'gender',
    sorter: true,
    valueType : "select",
    fieldProps : {
      options : [
        {label : '女',value : 0},
        {label : '男',value : 1},
      ]
    },
    // hideInSearch: true,
  },
  {
    title: '电话',
    dataIndex: 'phone',
  },
  {
    title: '邮箱',
    dataIndex: 'email',
  },
  {
    title: '状态',
    dataIndex: 'userStatus',
    valueType : "switch",
    // fieldProps : {
    //   options : [
    //     {label : '无效',value : 0},
    //     {label : '有效',value : 1},
    //   ]
    // },
    renderFormItem: (_, { defaultRender }) => {
      return defaultRender(_);
    },
    render: (_, record) => (
      <Switch defaultChecked={record.userStatus === 1 } checkedChildren="有效" unCheckedChildren="无效"
              onClick={function(checked: boolean){
                  record.userStatus = checked ? 1 : 0;
                  updateRow(record)
              }}>
      </Switch>
    ),

  },
  {
    title: '操作',
    valueType: 'option',
    key: 'option',
    render: (text, record, _, action) => [
      <a
        key="editable"
        onClick={() => {
          action?.startEditable?.(record.id);
        }}
      >
        编辑
      </a>,
      <a href={record.url} target="_blank" rel="noopener noreferrer" key="view">
        查看
      </a>,
      <TableDropdown
        key="actionGroup"
        onSelect={() => action?.reload()}
        menus={[
          { key: 'copy', name: '复制' },
          { key: 'delete', name: '删除' },
        ]}
      />,
    ],
  },
];

export default () => {
  const actionRef = useRef<ActionType>();
  return (
    <ProTable<GithubIssueItem>
      columns={columns}
      actionRef={actionRef}
      cardBordered
      request={async (params, sort, filter) => {
        console.log(sort, filter);
        await waitTime(2000);
        const userList = await search();
        return { data : userList}
      }}
      editable={{
        type: 'multiple',
        onSave : async (rowKey, data, row) => {
          const user : API.CurrentUser = {
            ...data
          }
          try {
            const result = updateUser(user);
            if (result) {
              message.success("修改成功")
            } else {
              message.error("修改失败")
            }
            actionRef.current?.reload();
          } catch (e) {
            message.error(e.message)
          }
        },
        onDelete : async (key,row)=>{
          const deleteParam : API.DeleteParams = {
            id : key
          }
          const result = deleteUser(deleteParam);
          showMessage(result,result ? "删除成功" : "删除失败")
          actionRef.current?.reload()
        }
      }}
      columnsState={{
        persistenceKey: 'pro-table-singe-demos',
        persistenceType: 'localStorage',
        defaultValue: {
          option: { fixed: 'right', disable: true },
        },
        onChange(value) {
          console.log('value: ', value);
        },
      }}
      rowKey="id"
      search={{
        labelWidth: 'auto',
      }}
      options={{
        setting: {
          listsHeight: 400,
        },
      }}
      form={{
        // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
        syncToUrl: (values, type) => {
          if (type === 'get') {
            return {
              ...values,
              created_at: [values.startTime, values.endTime],
            };
          }
          return values;
        },
      }}
      pagination={{
        pageSize: 5,
        onChange: (page) => console.log(page),
      }}
      dateFormatter="string"
      headerTitle="高级表格"
      toolBarRender={() => [
        <Button
          key="button"
          icon={<PlusOutlined />}
          onClick={() => {
            actionRef.current?.reload();
          }}
          type="primary"
        >
          新建
        </Button>,
        <Dropdown
          key="menu"
          menu={{
            items: [
              {
                label: '1st item',
                key: '1',
              },
              {
                label: '2nd item',
                key: '1',
              },
              {
                label: '3rd item',
                key: '1',
              },
            ],
          }}
        >
          <Button>
            <EllipsisOutlined />
          </Button>
        </Dropdown>,
      ]}
    />
  );
};
